<template>
  <div class="toDoWorkOrderInform">
    <div style="bottom: 74px;top: 100px;position: fixed;">
      <div class="toDoWorkOrderContainer">
        <div class="basicInform">
          <table class="basicInformTable">
            <caption>基本信息</caption>
            <tr>
              <th scope="col"></th>
              <th scope="col"></th>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>标题</td>
              <td class="td2">
                <span>{{ form.title }}</span>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>主送对象</td>
              <td class="td2">
                <template v-for="receiverNames in form.receiverName">
                  <template v-for="receiverName in receiverNames">
                    <span>{{ receiverName.name }}</span>&nbsp;&nbsp;
                  </template>

                </template>

              </td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>日期</td>
              <td class="td2">
                <span>{{ form.createTime }}</span>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>拟稿部门</td>
              <td class="td2">
                <span>{{ form.creatorDeptName }}</span>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>拟稿人</td>
              <td class="td2">
                <span>{{ form.creatorName }}</span>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>拟稿人电话</td>
              <td class="td2">
                <span>{{ form.creatorMobile }}</span>
              </td>
            </tr>
          </table>
        </div>
        <div class="taskInform">
          <div class="taskInform_h3">
            <h3>任务信息</h3>
          </div>
          <div class="taskName">
            <table>
              <caption>任务信息</caption>
              <tr>
                <th scope="col"></th>
                <th scope="col"></th>
              </tr>
              <template v-if="form.mainWorkApplyInfo">
                <tr>
                  <td class="td1">任务派发人</td>
                  <td class="taskName_content">{{ form.distributeName }}</td>
                </tr>
                <tr>
                  <td colspan="2">
                    <hr class="hrStyle"/>
                  </td>
                </tr>
                <tr>
                  <td class="td1">平级办理人</td>
                  <td class="taskName_content">{{ form.otherHandlerName }}</td>
                </tr>
                <tr>
                  <td colspan="2">
                    <hr class="hrStyle"/>
                  </td>
                </tr>
              </template>
              <tr>
                <td class="td1"><span class="red-span">*</span>主任务描述</td>
                <td class="taskName_content"><span>{{ form.mainTaskName }}</span></td>
              </tr>
            </table>
          </div>


          <table v-for="(subTaskItem,index) in workApplyData.data.subTasks" :key="subTaskItem.id" class="subTaskTable">
            <caption>分任务信息</caption>
            <tr>
              <th scope="col"></th>
              <th scope="col"></th>
            </tr>
            <tr>
              <td class="th">
                <div class="subAskName">
                  <h4>分任务{{ index + 1 > 9 ? index + 1 : "0" + (index + 1) }}</h4>
                </div>
              </td>
              <td class="th">
                <div class="btn_work">
                  <span v-if="showUrgeBtn(subTaskItem)" @click="urgeTask(subTaskItem.id)">催办</span>
                </div>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>分任务名称</td>
              <td class="td2"><span>{{ subTaskItem.name }}</span></td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>内容、要求描述</td>
              <td class="td2"><span>{{ subTaskItem.description }}</span></td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>要求完成日期</td>
              <td class="td2">
                <span>{{ subTaskItem.finishTime }}</span>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="hrStyle"/>
              </td>
            </tr>
            <tr>
              <td class="td1"><span class="red-span">*</span>分任务附件</td>
              <td class="td2"></td>
            </tr>
            <tr>
              <td colspan="2">
                <hr class="td_hr"/>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="taskTemplate">
                  <template v-if="subTaskItem.templateAttachments.length > 0">
                    <span>模板附件</span>
                    <div v-for="templateAttachment in subTaskItem.templateAttachments" :key="templateAttachment.id">
                      <br/>
                      <em class="iconfont icon-fujian"/>
                      <a @click="uploadTemplateFile(templateAttachment.id)">&nbsp;{{ templateAttachment.fileName }}</a>
                      <br/>
                    </div>
                    <br/>
                  </template>
                  <template v-if="subTaskItem.reportAttachments.length > 0">
                    <br/>
                    <span>上报附件</span>
                    <div v-for="reportAttachment in subTaskItem.reportAttachments" :key="reportAttachment.id">
                      <br/>
                      <em class="iconfont icon-fujian"/>
                      <a @click="uploadTemplateFile(reportAttachment.id)">&nbsp;{{ reportAttachment.fileName }}</a>
                      <br/>
                    </div>
                    <br/>
                  </template>
                  <template v-if="subTaskItem.mergeAttachments.length > 0">
                    <br/>
                    <span>合并报表附件</span>
                    <div v-for="mergeAttachment in subTaskItem.mergeAttachments" :key="mergeAttachment.id">
                      <br/>
                      <em class="iconfont icon-fujian"/>
                      <a @click="uploadTemplateFile(mergeAttachment.id)">&nbsp;{{ mergeAttachment.fileName }}</a>
                      <br/>
                    </div>
                    <br/>
                  </template>
                </div>
              </td>
            </tr>
          </table>

          <table class="attachTemplate" v-if="workApplyData.data.referenceAttachments?.length > 0">
            <caption>参考附件</caption>
            <tr>
              <th scope="col"></th>
              <th scope="col"></th>
            </tr>
            <tr>
              <td class="attachTemplate_td1">参<br/>考<br/>附<br/>件</td>
              <td class="attachTemplate_td2">
                <div v-for="attachmentsItem in workApplyData.data.referenceAttachments" :key="attachmentsItem.id">
                  <br/>
                  <em class="iconfont icon-fujian"/>
                  <a @click="uploadTemplateFile(attachmentsItem.id)">&nbsp;{{ attachmentsItem.fileName }}</a>
                  <br/>
                </div>
              </td>
            </tr>
          </table>
          <div style="display: none">
            <div class="subtitle">
              <h4>统计分析</h4>
            </div>
            <table class="statist">
              <caption>统计分析</caption>
              <tr>
                <th scope="col"></th>
                <th scope="col"></th>
              </tr>
              <tr>
                <td class="td3">方烨</td>
                <td class="td4">15%</td>
              </tr>
              <tr>
                <td colspan="2">
                  <hr class="hrStyle"/>
                </td>
              </tr>
            </table>
          </div>

          <template v-if="displayBlock">
            <div class="taskInform_h3">
              <h3>完成统计</h3>
            </div>
            <div class="subtitle">
              <h4>完成情况</h4>
            </div>
            <table class="statist">
              <caption>完成情况</caption>
              <tr>
                <th scope="col"></th>
                <th scope="col"></th>
              </tr>

              <template v-for="(subTaskItem,index) in workApplyData.data.subTasks">
                <tr>
                  <td class="td3">{{ subTaskItem.name }}</td>
                  <td class="td4">
                    <input type="text" v-model="xData[index]" readonly="readonly"/>%
                  </td>
                </tr>
                <tr v-if="index !== workApplyData.data.subTasks.length -1">
                  <td colspan="2">
                    <hr class="hrStyle"/>
                  </td>
                </tr>
              </template>

            </table>
            <div class="taskInform_h3">
              <h3>办理情况</h3>
            </div>

            <table class="finishJobTable">
              <caption>办理情况</caption>
              <tr>
                <th scope="col"></th>
                <th scope="col"></th>
              </tr>
              <template v-for="(itemData,index1) in workApplyParentData?.data">
                <template v-for="(items,index2) in itemData.subTasks">
                  <tr class="tr1">
                    <td class="td1">{{
                        index1 * itemData.subTasks.length + index2 + 1 > 9 ? index1 * itemData.subTasks.length + index2 + 1 : "0" + (index1 * itemData.subTasks.length + index2 + 1)
                      }}
                    </td>
                    <td class="td2">
                      <div class="btn_button" v-if="showBtnButton">
                        <template v-if="canViewOperateButton(items.node)">
                          <div :ref="'changeStyle'+(index1 * itemData.subTasks.length + index2 + 1)">
                            <span class="btn_back"
                                  @click="confirmSimpleTask(items.id, items.parentWorkApplyId , false, '退回意见',index1 * itemData.subTasks.length + index2 + 1)">退回</span>
                            <span class="btn_confirm"
                                  @click="confirmSimpleTask(items.id, items.parentWorkApplyId, true, '同意',index1 * itemData.subTasks.length + index2 + 1)">确认</span>
                          </div>
                        </template>
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td class="td1">分任务名称</td>
                    <td class="td2">{{ items.name }}</td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <hr class="hrStyle"/>
                    </td>
                  </tr>
                  <tr>
                    <td class="td1">主办人</td>
                    <td class="td2">{{ itemData.assignUserName }}</td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <hr class="hrStyle"/>
                    </td>
                  </tr>
                  <tr>
                    <td class="td1">上报附件</td>
                    <td class="td2">
                      <template v-for="reportAttachment in items.reportAttachments">
                        <a @click="uploadTemplateFile(reportAttachment.id)"
                           style="color: blue">{{ reportAttachment.fileName }}</a>
                        <br/>
                      </template>
                    </td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <hr class="hrStyle"/>
                    </td>
                  </tr>
                  <tr>
                    <td class="td1">状态</td>
                    <td class="td2">{{ items.nodeName }}</td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <hr class="hrStyle"/>
                    </td>
                  </tr>
                  <tr>
                    <td class="td1">最后更新日期</td>
                    <td class="td2">{{ items.updateTime }}</td>
                  </tr>
                </template>
              </template>
            </table>
          </template>

          <template v-if="showOpinion">
            <div class="taskInform_h3">
              <h3>审批意见</h3>
            </div>
            <div class="textArea">
              <textarea v-model="opinion" placeholder="请输入"></textarea>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="workOrderFooter">
      <div class="work-bts-cls">

        <button class="op-bt-cls" v-if="workProp.showSubmitDraft" @click="submitDraft(form,opinion)">
          提交
        </button>

        <button class="op-bt-cls" v-if="workProp.showSubmit"
                @click="submitTask()">
          提交
        </button>

        <button class="op-bt-cls" v-if="workProp.showReport" @click="reportForm(form,workApplyData.tiid,opinion)">
          上报
        </button>

        <button class="op-bt-cls" v-if="workProp.showConfirm" @click="confirmSimpleTask()">
          确认
        </button>


        <button class="op-bt-cls" v-if="workProp.showTransfer">
          转交
        </button>

        <button class="op-bt-cls" v-if="workProp.showReject" @click="rejectTask()">
          退回
        </button>

        <button class="op-bt-cls" v-if="workProp.showFinish"
                @click="finishConfirm()">
          办结
        </button>

        <button class="op-bt-cls" v-if="workProp.showBack" @click="backBtn()">
          返回
        </button>

      </div>
    </div>
  </div>

</template>

<script>
import API from "@/api/api-chat-list";
import {isEmpty} from "@/common/util";
import AesGcm from "@/utils/aesgcm";

const STATUS_NAME_MAP = {
  "DRAFT": "草稿",
  "DEPT_ADMIN_APPROVE": "部门管理员审批",
  "CREATE_SUB_FLOW": "分任务子流程",
  "RESPONDER_APPROVE": "责任人审批",
  "SUB_ORG_USER_HANDLE": "子流程-组织人员办理",
  "SUB_CREATE_SUB_FLOW": "子流程-分任务办理子流程",
  "SUB_ORG_USER_CONFIRM": "子流程-组织人员确认",
  "SUB_CREATOR_CONFIRM": "子流程-拟稿人确认",
  "END": "处理完成"
}
const FINISH_NODE_FOR_HANDLER = ['FINISH', 'SUPERIOR_CONFIRM'];

export default {
  name: "ToDoWorkOrder",
  props: [
    "workApplyData",
  ],
  data() {
    return {
      form: {
        title: this.workApplyData.data.title,
        receiverName: JSON.parse(this.workApplyData.data.receiverName),
        createTime: this.workApplyData.data.createTime,
        creatorDeptName: this.workApplyData.data.creatorDeptName,
        creatorName: this.workApplyData.data.creatorName,
        creatorMobile: this.workApplyData.data.creatorMobile,
        mainTaskName: this.workApplyData.data.mainTaskName,
        mainWorkApplyInfo: this.workApplyData.data.mainWorkApplyInfo,
        otherHandlerName: this.workApplyData.data.otherHandlerName,
        distributeName: null,
      },
      workProp: {
        showBack: true,
        showSubmitDraft: false,
        showSubmit: false,
        showSave: false,
        showConfirm: false,
        showReport: false,
        showTransfer: false,
        showReject: false,
        showFinish: false,
      },
      opinion: '',
      displayBlock: false,
      xData: [],
      yData: null,
      readOnly: true,
      showOpinion: true,
      showBtnButton: true,
      taskData: {},
      workApplyParentData: this.$store.state.workApplyParentData,
    }
  },
  async created() {
    const taskId = this.workApplyData?.tiid;
    if (!isEmpty(taskId)) {
      const paramTaskId = {
        taskId
      }
      this.taskData = await API.getTaskByTiid(paramTaskId);
    }else{
      return;
    }
    await this.showBottomButton();
    this.querry();
    if(this.form.mainWorkApplyInfo){
      this.form.title = this.form.mainWorkApplyInfo.title;
      this.form.receiverName = JSON.parse(this.form.mainWorkApplyInfo.receiverName);
      this.form.createTime = this.form.mainWorkApplyInfo.createTime;
      this.form.creatorDeptName = this.form.mainWorkApplyInfo.creatorDeptName;
      this.form.creatorName = this.form.mainWorkApplyInfo.creatorName;
      this.form.creatorMobile = this.form.mainWorkApplyInfo.creatorMobile;
      this.form.distributeName = this.form.creatorName;
    }
  },
  methods: {
    async reportForm(workApplyInfo, taskId, opinion) {
      const param = {
        workApplyInfo,
        taskId,
        "fileRes": "",
        "opinion": opinion + "(手机)",
      }
      await API.report(param);

    },
    async submitDraft(workApplyInfo, opinion) {
      const param = {
        workApplyInfo,
        "file": "",
        "fileRes": "",
        "opinion": opinion + "(手机)",
      }
      await API.submitDraft(param);

    },
    // 管理员审批提交
    async submitTask() {
      const fd = new FormData();
      fd.append('workApplyId', this.workApplyData.data.id);
      fd.append('taskId', this.workApplyData.tiid);
      fd.append('opinion', this.opinion + "(手机)");
      await API.submitTask(fd);
      this.$store.commit('setWorkOrderType', "workOrderInform");
      this.$router.back();
    },
    // 管理员审批办结
    async finishConfirm() {
      const fd = new FormData();
      fd.append('workApplyId', this.workApplyData.data.id);
      fd.append('taskId', this.workApplyData.tiid);
      fd.append('opinion', this.opinion + "(手机)");
      await API.finishConfirm(fd);
      this.$store.commit('setWorkOrderType', "workOrderInform");
      this.$router.back();

    },
    // 确认流程
    async confirmSimpleTask(subTaskIds, workApplyId, state, msg, index) {
      const fd = new FormData();
      fd.append('workApplyId', workApplyId);
      fd.append('subTaskIds', subTaskIds);
      if (state) {
        fd.append('confirm', state);
      }
      fd.append('opinion', msg);
      const resultDate = await API.confirmSimpleTask(fd);
      if (resultDate.parentWorkApplyInfoStatus === 'FINISH_CONFIRM') {
        this.workProp.showFinish = true;
      }
      this.$refs[`changeStyle${index}`][0].style = 'display: none';
      this.querry();

    },
    // 部门管理员回退
    async rejectTask() {
      const fd = new FormData();
      fd.append('workApplyId', this.workApplyData.data.id);
      fd.append('taskId', this.workApplyData.tiid);
      fd.append('opinion', this.opinion + "(手机)");
      await API.rejectTask(fd);
    },
    // 回退流程
    async rejectSimpleTask(subApplyId, workApplyId) {
      const fd = new FormData();
      fd.append('workApplyId', workApplyId);
      fd.append('subApplyId', subApplyId);
      fd.append('taskId', this.workApplyData.tiid);
      fd.append('opinion', this.opinion + "(手机)");
      await API.rejectSimpleTask(fd);
      this.showBtnButton = false;
    },
    uploadTemplateFile(attachmentId) {
      const fileUrl = AesGcm.decrypt(process.env.VUE_APP_INTERFACE_URL) + '/api/work/downloadAttachment?attachmentId=' + attachmentId;
      MXCommon.download(fileUrl);  //下载文件
    },
    // 返回上一页
    backBtn() {
      this.$store.commit('setWorkOrderType', "workOrderInform");
      this.$router.back();
    },
    // 计算任务完成度百分比
    querry() {
      const res = this.workApplyParentData;
      if (res?.data?.length > 0) {
        const subApplys = res.data;
        // 单个分任务百分比计算公式：已完成该分任务的主送对象个数，除以全部主送对象个数。
        const subApplysSubTasks = subApplys.flatMap(subApply => subApply.subTasks);
        // 这个是主工单分任务
        this.yData = this.workApplyData.data.subTasks.map(item => {
          return item.name
        })
        // x轴统计时，顺序应该跟y轴对应
        this.xData = this.workApplyData.data.subTasks.map(item => {
          // 单个分任务 item
          const finishSubTask = subApplysSubTasks.filter(subItem => {
            return subItem.parentTaskId === item.id && subItem.state === 'FINISH'
          })
          // 分任务的数量就是主送对象的数量
          const total = this.form.receiverName.length;
          const percentage = (finishSubTask.length / total) * 100
          return percentage.toFixed(2)
        })
      }
    },
    // 确认/回退按钮隐藏/显示判断,办结按钮显示/隐藏
    canViewOperateButton(state) {
      return state === 'SUPERIOR_CONFIRM' && this.taskData?.data?.state === 1;
    },
    // 初始化底部按钮
    async showBottomButton() {
      const paramApplyParentId = {
        "parentId": this.workApplyData.data.id,
      }

      //获取父类工单信息

      this.displayBlock = this.workApplyData.data.dispatched;
      this.workApplyParentData = this.workApplyData.data.dispatched ? await API.findWorkApplyByParentId(paramApplyParentId) : null;
      const array = [1, 4];
      if (array.includes(this.taskData?.data?.state)) {
        switch (this.workApplyData.data.status) {
          case 'DEPT_ADMIN_APPROVE':
            this.workProp.showSubmit = true;
            this.workProp.showReject = true;
            break;
          case 'FINISH_CONFIRM':
            this.workProp.showFinish = true;
            break;
          default:
            this.showOpinion = false;
        }
      } else {
        this.showOpinion = false;
      }
    },
    // 催办按钮显示判断: 1、当前用户是工单创建用户 2、有子工单，且子工单分任务未上报未完成
    showUrgeBtn(subTask){
      const userInfoUid = this.$store.state.userInfo.userID;
      const creatorUid = this.workApplyData.data.creatorUid;
      if(userInfoUid !== creatorUid){
        return false;
      }

      const subApplyHaveNotReport = this.workApplyParentData?.data.flatMap(subApply => subApply.subTasks)
        .some(subApplySubTask => subApplySubTask.parentTaskId === subTask.id && !FINISH_NODE_FOR_HANDLER.includes(subApplySubTask.node));
      return this.workApplyParentData?.data && subApplyHaveNotReport;

    },
    // 催办任务
    async urgeTask(subTaskIds) {
      const param = {
        subTaskIds: subTaskIds,
      }
      await API.urgeTask(param);
    },
  },
  filters: {
    showStatus(status) {
      return STATUS_NAME_MAP[status];
    }
  }
}
</script>

<style scoped>
@import url("~@/assets/css/workOrder/ToDoWorkOrder.css");
</style>
